import axios from 'axios'
import router from '@/router'
import { Message } from 'element-ui'
import { v4 as uuidv4 } from 'uuid'
import { show, cancel } from '@/utils/commonLoading.js'
import * as Cookies from 'js-cookie'
import qs from 'qs'
import store from '@/store'

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 20000
})

service.interceptors.request.use(
    config => {
        console.log('config.params: ' + JSON.stringify(config.params))
        console.log('config.data: ' + JSON.stringify(config.data))
        if (config.method === 'get') {
            config.paramsSerializer = function(params) {
                return qs.stringify(params, { arrayFormat: 'repeat' })
            }
        }
        const token = Cookies.get('token')
        console.log('request token: ' + token)
        if (token) {
            config.headers.Authorization = token
        } else {
            //
            config.headers.Authorization = 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJocXEiLCJzY29wZSI6WyJhbGwiXSwicm9sZXMiOlsiMl_nrqHnkIblkZgiLCI0X-W8gOWPkeS6uuWRmCJdLCJpZCI6IjE4ZjMwN2FhODk3MTRmMjViNWExYzhmNTIyZDBmZTY5IiwiZXhwIjoxNjc5MzE3MTczLCJhdXRob3JpdGllcyI6WyIyX-euoeeQhuWRmCIsIjRf5byA5Y-R5Lq65ZGYIl0sImp0aSI6ImEzZThiNzUyLWUyMmUtNDJmZS1hOWY5LTBiNGQzMTNjNjVlNiIsImNsaWVudF9pZCI6ImFkbWluLWNlbnRlciIsInVzZXJuYW1lIjoiaHFxIiwic3RhdHVzIjoxfQ.NFMbgGynoMVy-koVkbnXoWWbokQFu_RfRGkuzSgrbqgSG3GgpSLKXJ-axa86QG1ZO4hqsg2odRmF2UAJ9ISLpTG_m_mRk5lJWcWTzvVFn98kYqxw7S6vXAFcD0FU1bFa6cf4LpjTJyBpPBek_g7dyQUP7x276aDkjvutunEkNgQ'
        }
        // 处理loading
        if (config.data && config.data.loadingTarget) {
            config.uuid = uuidv4()
            show(config.data.loadingTarget, config.uuid)
            delete config.data.loadingTarge
        }
        return config //  请求头部抛出
    },
    error => {
        console.error(error)
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        if (response.config.uuid) {
            cancel(response.config.uuid)
        }
        const res = response.data
        console.log('response: ' + JSON.stringify(response))
        // TODO 水表信息导入接口特殊处理
        // if (response.config.responseType === 'blob') {
        //     // if (response.headers['content-type'] === 'application/x-download;charset=UTF-8') {
        //     // console.log('response data: ' + JSON.stringify(response.data))
        //     return response.data
        //     // } else {
        //
        //     // }
        // }
        // console.log(res.code,window.location.host,'????????')
        if (res.code !== 200) {
            if (res.code == '1003') {
                store.dispatch('user/setLoginStatus',res)
            } else if (res.code == '1001') {
                store.dispatch('user/setLoginStatus',res)
            } else if (res.code == '1002') {
                store.dispatch('user/setLoginStatus',res)
            } else if (res.code !== 300 && res.code !== 501) {
                Message.error(res.message)
            }
            // 300 状态码报错表示字段名称重复F
            // if (res.code !== 300) {
            //   Message.error(res.message)
            // }
            // 401 状态码 重新登录
            if (res.code === 401) {
                // 跳转主系统登录页
                Cookies.remove('token')
                // let url = window.location.host+'/dongqufpc/#/login'
                // window.open(url,'_self')
                setTimeout(()=>{
                    window.close()
                },1000)
                // window.location.href = window.location.host + '/dongqupc/#/login'
            }
            // Message({
            //   message: res.message || 'Error',
            //   type: 'error',
            //   duration: 2 * 1000
            // })
            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            return res
        }
    },
    error => {
        console.error(error)
        Message({
            message: error.message,
            type: 'error',
            duration: 2 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
